package com.fand.stater.interceptor;

import java.util.Date;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import com.fand.stater.constant.EventCodeEnum;
import com.fand.stater.context.UserInfoThreadLocal;
import com.fand.stater.handler.SysUserESIndexRecordHandler;
import com.fand.stater.model.SysUserDetailDTO;
import com.fand.stater.model.es.SysUserESIndexRecord;
import com.fand.common.util.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * Author: zhangjiabin
 * Email: javaboyok@163.com
 * CreateDate: 2021/6/26
 * Version: 1.0
 */
@Slf4j
public class IndexUserInfoInterceptor implements HandlerInterceptor {


    private SysUserESIndexRecordHandler sysUserESIndexRecordHandler;

    public IndexUserInfoInterceptor(SysUserESIndexRecordHandler sysUserESIndexRecordHandler) {
        this.sysUserESIndexRecordHandler = sysUserESIndexRecordHandler;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        SysUserDetailDTO sysUserDetailDTO = UserInfoThreadLocal.get();
        if(Objects.isNull(sysUserDetailDTO)){
            return true;
        }
        /**
         * 统计日活用户
         */
        if("/index".equals(request.getRequestURI())){
            SysUserESIndexRecord sysUserESIndexRecord = SysUserESIndexRecord.builder()
                    .dateTime(DateUtil.formatDateTime(new Date()))
                    .time(System.currentTimeMillis())
                    .ip(request.getRemoteHost())
                    .address(IPUtil.ip2Address(request.getRemoteHost()))
                    .UserId(sysUserDetailDTO.getId())
                    .userName(sysUserDetailDTO.getRealName())
                    .userCode(sysUserDetailDTO.getUsername())
                    .eventCode(EventCodeEnum.INDEX.getCode())
                    .build();
            sysUserESIndexRecordHandler.sendRecord(sysUserESIndexRecord);
        }
        return true;
    }
}
